package cn.zhf.shop.controller;

import cn.zhf.shop.entity.Message;
import cn.zhf.shop.entity.Shopping;
import cn.zhf.shop.service.ShoppingService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@Api(tags = "购物车模块")
@RequestMapping("/api/shopping/")
public class ShoppingController {

    @Resource
    private ShoppingService shoppingService;

    @PostMapping("/")
    @ApiOperation(value = "增加购物车")
    public Message insert(Shopping shopping){
        if (shoppingService.countByUserId(shopping.getUserId())>99)
        {
            return Message.fail("购物车已达到上限！");
        }
        else
        {
            Shopping shopping2=shoppingService.selectByUserIdAndLessonId(shopping.getUserId(),shopping.getLessonId());
            if (shopping2!=null){
                //如果购物车存在此商品，更换数量
                return shoppingService.updateLessonNumByShoppingId(shopping2.getShoppingId(),shopping.getLessonNum());
            }else{
                return shoppingService.insertSelective(shopping);
            }
        }

    }

    @DeleteMapping("/")
    @ApiOperation(value = "删除购物车")
    public Message delete(int shoppingId){
        return shoppingService.deleteByPrimaryKey(shoppingId);
    }

    @PutMapping("/num")
    @ApiOperation(value = "修改购物车的商品的数量")
    public Message updatenum(int shoppingId,int num){
        return shoppingService.updateLessonNumByShoppingId(shoppingId,num);
    }

    @GetMapping("/")
    @ApiOperation(value = "根据userid查看购物车")
    public Message<List<Shopping>> selectByUserId(String userId){
        return shoppingService.selectAllByUserId(userId);
    }
}
